/**
 * @Title: SpringExceptionHandler.java
 * @Package com.hfi.common.mvc
 * @author YangChaofeng 2016年4月29日 下午3:07:37
 * @Description: spring统一处理异常信息
 */
package com.mililoan.console.tools;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.mililoan.common.bean.CommonResult;
import com.mililoan.common.exception.BusinessException;
import com.mililoan.common.exception.SessionTimeoutException;
import com.mililoan.common.utils.StackTraceUtil;

/**
 * @ClassName: SpringExceptionHandler
 * @Description: spring统一处理异常信息
 * @author YangChaofeng 2016年4月29日 下午3:07:37
 */
public class SpringExceptionHandler implements HandlerExceptionResolver {
	private static Logger LOGGER = LoggerFactory.getLogger(SpringExceptionHandler.class);

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("exception", ex);

		String view = "common/sessionTimeout";

		if (!(ex instanceof SessionTimeoutException)) {
			view = "common/error";
 		}

		// 根据不同错误转向不同页面
		if (ex instanceof BusinessException) {
			LOGGER.error(StackTraceUtil.getStackTrace(ex));
			model.put("exceptionType", "BusinessException");
		} else if (ex instanceof SessionTimeoutException) {
			model.put("exceptionType", "SessionTimeoutException");
			//String path = request.getServletPath();
		} else if (ex instanceof NullPointerException) {
			LOGGER.error(StackTraceUtil.getStackTrace(ex));
			model.put("exceptionType", "NullPointerException");
		} else if (ex instanceof SQLException) {
			LOGGER.error(StackTraceUtil.getStackTrace(ex));
			model.put("exceptionType", "SQLException");
		} else {
			LOGGER.error(StackTraceUtil.getStackTrace(ex));
			model.put("exceptionType", "Exception");
		}
		if (WebUtil.isAjaxRequest()) {
			try {
				CommonResult res = new CommonResult(CommonResult.FAIL, (String) model.get("exceptionType"), model);
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json");
				response.getWriter().write(JSON.toJSONString(res));
			} catch (IOException e) {
				LOGGER.error(StackTraceUtil.getStackTrace(e));
			}

			return null;
		} else {
			return new ModelAndView(view, model);
		}
	}

}
